import TencentCloudChat, { Group, GroupMember } from '@tencentcloud/chat'
import { useMitt } from '@/hooks/useMitt.ts'
import { useTencentChat } from '@/stores/tencentChat.ts'
import { useTencentUserStore } from '@/stores/tencentUserStore.ts'
import { useTencentConversationStore } from '@/stores/tencentConversationStore.ts'

export const useTencentGroupStore = defineStore(
  'TencentGroup',
  () => {
    const tencentChat = useTencentChat()
    const tencentConversationStore = useTencentConversationStore()
    const tencentUserStore = useTencentUserStore()
    // 当前群聊
    const currentGroup = ref<Partial<Group>>({})
    const groupMemberMap = reactive<Record<string, Record<string, Partial<GroupMember>>>>({})
    const groupMemberProfileMap = reactive<Record<string, Record<string, Partial<GroupMember>>>>({})
    const offsetMap = reactive<Record<string, string>>({})
    const offsetOfGroupAdminMap = reactive<Record<string, string>>({})
    const groupOnlineMemberCount = ref<number>(0)
    const groupProfileMap = reactive<Record<string, Partial<Group>>>({})
    const groupAdminMap = reactive<Record<string, Record<string, Partial<GroupMember>>>>({})
    const ownerID = computed(() => currentGroup.value.ownerID)
    const groupList = ref<Group[]>([])

    const getGroupProfile = async (options: any) => {
      await tencentChat.chat?.getGroupProfile(options).then((res) => {
        groupProfileMap[options.groupID] = res.data.group
      })
    }

    const setCurrentGroup = (groupID: string) => {
      currentGroup.value = groupProfileMap[groupID]
      console.log('current group', currentGroup.value)
    }

    const updateGroupProfile = (options: any) => {
      tencentChat.chat
        ?.updateGroupProfile(options)
        .then((res) => {
          groupProfileMap[options.groupID] = res.data.group

          useMitt.emit('groupNotification')
        })
        .catch((error) => {
          window.$message.error(error.message)
        })
    }

    const getGroupAdminList = (groupID: string) => {
      if (groupAdminMap[groupID] === undefined) {
        groupAdminMap[groupID] = {}
      }
      // console.log('group admin', groupAdminMap[groupID])

      const options = {
        groupID: groupID,
        role: 'Admin',
        count: 30,
        offset: offsetOfGroupAdminMap[groupID]
      }

      tencentChat.chat
        ?.getGroupMemberList(options)
        .then((res) => {
          // console.log('group member list', res)
          res.data.memberList.forEach((item: GroupMember) => {
            groupAdminMap[groupID][item.userID] = item
          })
          offsetOfGroupAdminMap[groupID] = res.data.offset
        })
        .catch((error) => {
          console.error('get group member list error', error)
        })
    }

    const getGroupMemberList = (groupID: string) => {
      if (groupMemberMap[groupID] === undefined) {
        groupMemberMap[groupID] = {}
      }

      // if (groupMemberProfileMap[groupID] === undefined) {
      //   groupMemberProfileMap[groupID] = {}
      // }

      if (offsetMap[groupID] === undefined) {
        offsetMap[groupID] = ''
      }
      // console.log('group member list', groupProfileMap[groupID],)
      // 已加载完成
      if (
        groupProfileMap[groupID] &&
        groupProfileMap[groupID].memberCount === Object.values(groupMemberMap[groupID]).length
      )
        return

      const options = {
        groupID: groupID,
        count: 100,
        offset: offsetMap[groupID]
      }

      tencentChat.chat
        ?.getGroupMemberList(options)
        .then((res) => {
          offsetMap[groupID] = res.data.offset
          res.data.memberList.forEach(async (value: GroupMember) => {
            // if (tencentUserStore.userProfileMap[value.userID] === undefined) {
            //   await tencentUserStore.getUserProfile({ userIDList: [value.userID] })
            // }
            groupMemberMap[groupID][value.userID] = value
            // groupMemberProfileMap[groupID][value.userID] = value
          })
        })
        .catch((error) => {
          console.error('get group member list error', error)
        })
    }

    const getGroupMemberProfile = async (options: any) => {
      if (groupMemberProfileMap[options.groupID] === undefined) {
        groupMemberProfileMap[options.groupID] = {}
      }

      await tencentChat.chat?.getGroupMemberProfile(options).then((res) => {
        res.data.memberList.forEach((item: GroupMember) => {
          groupMemberProfileMap[options.groupID][item.userID] = item
        })
      })
    }

    const getOneOfGroupMemberProfile = async (options: any) => {
      const res = await tencentChat.chat?.getGroupMemberProfile(options)
      return res.data.memberList[0]
    }

    const setGroupMemberNameCard = async (options: any) => {
      await tencentChat.chat?.setGroupMemberNameCard(options).then((res) => {
        console.log(res.data.group) // 设置后的群资料
        console.log(res.data.member) // 修改后的群成员资料
      })
    }

    const setGroupMemberCustomField = () => {
      tencentChat.chat
        ?.setGroupMemberCustomField({
          groupID: 'group1',
          memberCustomField: [{ key: 'group_member_test', value: 'test' }]
        })
        .then(function (imResponse) {
          console.log(imResponse.data.group) // 修改后的群资料
          console.log(imResponse.data.member) // 修改后的群成员资料
        })
        .catch(function (imError) {
          console.warn('setGroupMemberCustomField error:', imError) // 设置群成员自定义字段失败的相关信息
        })
    }

    const createGroup = (options: any) => {
      // options = {
      //   type: TencentCloudChat.TYPES.GRP_PUBLIC,
      //   name: '沙雕发骚群',
      //   memberList: [{
      //     userID: '深圳仔'
      //   }, {
      //     userID: '东莞仔'
      //   }] // 如果填写了 memberList，则必须填写 userID
      // }
      // 创建好友工作群
      tencentChat.chat
        ?.createGroup(options)
        .then(function (imResponse) {
          // 创建成功
          console.log(imResponse.data.group) // 创建的群的资料
          // 创建群时指定了成员列表，但是成员中存在超过了“单个用户可加入群组数”限制的情况
          // 一个用户 userX 最多允许加入 N 个群，如果已经加入了 N 个群，此时创建群再指定 userX 为群成员，则 userX 不能正常加群
          // SDK 将 userX 的信息放入 overLimitUserIDList，供接入侧处理
          console.log(imResponse.data.overLimitUserIDList) // 超过了“单个用户可加入群组数”限制的用户列表
        })
        .catch(function (imError) {
          console.warn('createGroup error:', imError) // 创建群组失败的相关信息
        })
    }

    const joinGroup = (options: any) => {
      options = {
        groupID: '沙雕发骚群',
        applyMessage: '我要加入群聊'
      }
      tencentChat.chat
        ?.joinGroup(options)
        .then(function (imResponse) {
          switch (imResponse.data.status) {
            case TencentCloudChat.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意
              break
            case TencentCloudChat.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
              console.log(imResponse.data.group) // 加入的群组资料
              break
            case TencentCloudChat.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
              break
            default:
              break
          }
        })
        .catch(function (imError) {
          console.warn('joinGroup error:', imError) // 申请加群失败的相关信息
        })
    }

    // 获取已加入的群组
    const getGroupList = () => {
      // 该接口默认只会拉取这些资料：群类型、群名称、群头像、最后一条消息的时间。
      tencentChat.chat
        ?.getGroupList()
        .then(function (imResponse) {
          console.log(imResponse.data.groupList) // 群组列表
          groupList.value = imResponse.data.groupList
        })
        .catch(function (imError) {
          console.warn('getGroupList error:', imError) // 获取群组列表失败的相关信息
        })
    }

    // 退出群组
    const quitGroup = async (groupID: string) => {
      await tencentChat.chat
        ?.quitGroup(groupID)
        .then(async function (imResponse) {
          window.$message.success('退出成功')
          console.log(imResponse.data.groupID) // 退出成功的群 ID
          await tencentConversationStore.deleteConversationByGroupID(groupID)

          // 删除本地缓存成员
          delete groupMemberProfileMap[groupID][tencentUserStore.myProfile?.userID!]
          delete groupMemberMap[groupID][tencentUserStore.myProfile?.userID!]
        })
        .catch(function (imError) {
          console.warn('quitGroup error:', imError) // 退出群组失败的相关信息
        })
    }

    // 解散群组
    const dismissGroup = async (groupID: string) => {
      await tencentChat.chat
        ?.dismissGroup(groupID)
        .then(async function (imResponse) {
          // 解散成功
          window.$message.success('解散成功')
          console.log(imResponse.data.groupID) // 被解散的群组 ID
          await tencentConversationStore.deleteConversationByGroupID(groupID)

          // 删除本地缓存成员及群资料
          groupMemberProfileMap[imResponse.data.groupID] = {}
          groupMemberMap[imResponse.data.groupID] = {}
          groupProfileMap[imResponse.data.groupID] = {}
        })
        .catch(function (imError) {
          console.warn('dismissGroup error:', imError) // 解散群组失败的相关信息
        })
    }

    // 转让群组
    const changeGroupOwner = (groupID: string, newOwnerID: string) => {
      tencentChat.chat
        ?.changeGroupOwner({
          groupID: groupID,
          newOwnerID: newOwnerID
        })
        .then(function (imResponse) {
          // 转让成功
          console.log(imResponse.data.group) // 群组资料
        })
        .catch(function (imError) {
          // 转让失败
          console.warn('changeGroupOwner error:', imError) // 转让群组失败的相关信息
        })
    }

    // 处理申请加群和邀请进群（同意或拒绝）
    const handleGroupApplication = () => {
      // 通过获取未决列表处理加群申请
      tencentChat.chat
        ?.getGroupApplicationList()
        .then(function (imResponse) {
          const { applicationList } = imResponse.data
          applicationList.forEach((item: any) => {
            if (item.applicationType === 0) {
              tencentChat.chat
                ?.handleGroupApplication({
                  handleAction: 'Agree', // 处理结果 Agree(同意) / Reject(拒绝)
                  application: { ...item }
                })
                .catch((error) => {
                  console.warn('handle group application error', error)
                })
            }
          })
        })
        .catch(function (imError) {
          console.warn('getGroupApplicationList error:', imError)
        })
    }

    //
    const setGroupMemberMuteTime = (options: any) => {
      options = {
        groupID: 'group1',
        userID: 'user1',
        muteTime: 600 // 禁言10分钟；设为0，则表示取消禁言
      }
      tencentChat.chat
        ?.setGroupMemberMuteTime(options)
        .then(function (imResponse) {
          console.log(imResponse.data.group) // 修改后的群资料
          console.log(imResponse.data.member) // 修改后的群成员资料
        })
        .catch(function (imError) {
          console.warn('setGroupMemberMuteTime error:', imError) // 禁言失败的相关信息
        })
    }

    const setGroupMemberRole = (options: { groupID: string; userID: string; role: TencentCloudChat.TYPES }) => {
      tencentChat.chat
        ?.setGroupMemberRole(options)
        .then(function (imResponse) {
          console.log(imResponse.data.group) // 修改后的群资料
          console.log(imResponse.data.member) // 修改后的群成员资料
          currentGroup.value = imResponse.data.group
          window.$message.success('设置成功')

          groupProfileMap[options.groupID] = imResponse.data.group
          groupMemberMap[options.groupID][options.userID] = imResponse.data.mamber
        })
        .catch(function (imError) {
          console.warn('setGroupMemberRole error:', imError) // 错误信息
          window.$message.error('设置失败: ', imError.message)
        })
    }

    const getGroupOnlineMemberCount = (groupID: string) => {
      // 查询直播群在线人数
      tencentChat.chat
        ?.getGroupOnlineMemberCount(groupID)
        .then(function (imResponse) {
          console.log(imResponse.data.memberCount)
          groupOnlineMemberCount.value = imResponse.data.memberCount
        })
        .catch(function (imError) {
          console.warn('getGroupOnlineMemberCount error:', imError) // 获取直播群在线人数失败的相关信息
        })
    }

    const searchGroupByID = (groupID: string) => {
      tencentChat.chat
        ?.searchGroupByID(groupID)
        .then(function (imResponse) {
          console.log('search group by id', imResponse)
          // const group = imResponse.data.group; // 群组信息
        })
        .catch(function (imError) {
          console.warn('searchGroupByID error:', imError) // 搜素群组失败的相关信息
        })
    }

    const deleteGroupMember = (options: any) => {
      // 非直播群踢出群成员
      tencentChat.chat
        ?.deleteGroupMember(options)
        .then(function (imResponse) {
          const { group, userIDList } = imResponse.data
          currentGroup.value = group
          groupProfileMap[group.groupID] = group
          userIDList.forEach((item: string) => {
            // 删除本地缓存成员及群资料
            delete groupAdminMap[group.groupID][item]
            delete groupMemberMap[group.groupID][item]
            delete groupMemberProfileMap[group.groupID][item]
          })
          window.$message.success('用户已移出群聊')
          console.log(group) // 删除后的群组信息
          console.log(userIDList) // 被删除的群成员的 userID 列表
        })
        .catch(function (imError) {
          window.$message.error('移除失败: ' + imError.message)
          console.warn('deleteGroupMember error:', imError) // 错误信息
        })
    }

    return {
      currentGroup,
      ownerID,
      groupAdminMap,
      getGroupProfile,
      updateGroupProfile,
      groupMemberProfileMap,
      getGroupMemberList,
      getGroupMemberProfile,
      setGroupMemberNameCard,
      createGroup,
      dismissGroup,
      quitGroup,
      changeGroupOwner,
      getGroupList,
      setGroupMemberMuteTime,
      setGroupMemberCustomField,
      handleGroupApplication,
      joinGroup,
      setGroupMemberRole,
      getGroupOnlineMemberCount,
      searchGroupByID,
      groupOnlineMemberCount,
      getOneOfGroupMemberProfile,
      deleteGroupMember,
      groupList,
      groupMemberMap,
      groupProfileMap,
      getGroupAdminList,
      setCurrentGroup
    }
  },
  {
    share: {
      enable: true,
      initialize: true
    }
  }
)
